import sys
import time
from PyQt5 import uic
from PyQt5.Qt import QApplication, QWidget, QThread
import pyautogui as pag
from PIL import Image, ImageQt, ImageGrab
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap
from win32gui import GetWindowText, GetForegroundWindow, GetWindowRect
import numpy as np
import random
import cv2


class MyThread(QThread):

    def __init__(self, spinbox_values):
        super().__init__()
        self._running = False
        self.spinbox_values = spinbox_values

    def run(self):
        self._running = True
        check_win = 0
        check_timeout = 0
        buff_timeout = 0


        while self._running and check_win < 10 and check_timeout < 5:
            if self.focus_window():
                if buff_timeout >= 50:
                    pag.press('2')
                    buff_timeout = 0
                    time.sleep(random.uniform(2.5, 5))
                time.sleep(random.uniform(0.5, 1))
                if self._running:
                    pag.press('1')
                    time.sleep(2)
                    if self._running:
                        result = self.getImage()
                        if result is not None:
                            x, y = result
                            pag.moveTo(x, y, random.uniform(0.2, 0.5))
                            time.sleep(random.uniform(0.2, 1.2))
                            if self._running:
                                pag.rightClick()
                                time.sleep(1)
                                pag.moveTo(1850 + random.uniform(20, 50), 800 - random.uniform(30, 200),
                                           random.uniform(0.2, 0.5))
                                check_timeout = 0
                                buff_timeout += 1
                                continue
                        else:
                            check_timeout += 1
                            print(f"未接收到坐标: {check_timeout}次")
            else:
                check_win += 1
                print(f"自动退出倒计时：{6 - check_win}")
                continue
        print("线程已停止")

    def stop(self):
        self._running = False

    def focus_window(self):
        if GetWindowText(GetForegroundWindow()) != "魔兽世界":
            # print("请将控制窗口置于前端")
            time.sleep(1)
            return False
        else:
            # print("获取到指定窗口")
            return True

    def getImage(self):
        min_h, min_s, min_v, max_h, max_s, max_v = self.spinbox_values
        # print(h, s, v)
        start_time = time.time()
        while self._running:
            img_area = (700, 200, 1200, 600)

            img = ImageGrab.grab(img_area)
            img_np = np.array(img)

            frame = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
            frame_hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

            lower = np.array((min_h, min_s, min_v), np.uint8)
            # 100, 100, 250 / 0, 0, 253
            upper = np.array((max_h, max_s, max_v), np.uint8)
            # 140, 255, 253 / 255, 0, 255 / 158, 0, 255

            mask = cv2.inRange(frame_hsv, lower, upper)

            moments = cv2.moments(mask, False)
            end_time = time.time()
            if moments['m00'] > 0:  # 确保区域不为空
                dM01 = moments['m01']
                dM10 = moments['m10']
                dArea = moments['m00']
                # break
                # print('FIND')

                m_x = int(dM10 / dArea)
                m_y = int(dM01 / dArea)
                # window.label_point.setText(f"坐标: {str(m_x)} {str(m_y)}")
                # window.label_point.adjustSize()
                # 这里可以添加更多处理，如计算质心等
                # if self.focus_window():
                #     pag.moveTo(m_x + 702, m_y + 200, 0.3)
                #     break
                # else:
                #     # print("未找到控制界面")
                #     break
                return m_x + 700, m_y + 200
            elif end_time - start_time > 17:
                print(f"{time.ctime()} -> Time out")
                return None

            # cv2.imshow("mask", mask)
            # cv2.imshow("frame", frame)


class ImageProcThread(QThread):
    def __init__(self):
        super().__init__()
        self.running = False

    def run(self):
        self.running = True

        def empty(val):
            print(val)

        img_area = (700, 200, 1200, 600)
        screenshot = ImageGrab.grab(img_area)
        screenshot.save('proc_img.png')
        img = cv2.imread('./proc_img.png')
        img = cv2.resize(img, (380, 380))
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        cv2.namedWindow('trackbar', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('trackbar', width=500, height=200)
        cv2.createTrackbar('hue-min', 'trackbar', 0, 180, empty)
        cv2.createTrackbar('hue-max', 'trackbar', 180, 180, empty)
        cv2.createTrackbar('sat-min', 'trackbar', 0, 255, empty)
        cv2.createTrackbar('sat-max', 'trackbar', 255, 255, empty)
        cv2.createTrackbar('val-min', 'trackbar', 0, 255, empty)
        cv2.createTrackbar('val-max', 'trackbar', 255, 255, empty)

        while True:
            h_min = cv2.getTrackbarPos('hue-min', 'trackbar')
            h_max = cv2.getTrackbarPos('hue-max', 'trackbar')
            s_min = cv2.getTrackbarPos('sat-min', 'trackbar')
            s_max = cv2.getTrackbarPos('sat-max', 'trackbar')
            v_min = cv2.getTrackbarPos('val-min', 'trackbar')
            v_max = cv2.getTrackbarPos('val-max', 'trackbar')

            lower = np.array([h_min, s_min, v_min])
            upper = np.array([h_max, s_max, v_max])
            print(f"最小范围：{lower}\n最大范围：{upper}")
            mask = cv2.inRange(hsv, lower, upper)

            res = cv2.bitwise_and(img, img, mask=mask)
            cv2.imshow('mask', mask)
            cv2.imshow('result', res)
            cv2.imshow('img', img)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        cv2.destroyAllWindows()
        self.running = False

    def stop(self):
        self.running = False


class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.setFixedSize(207, 143)

    def init_ui(self):
        self.ui = uic.loadUi("./ui2.ui")

        btn1 = self.ui.pushButton
        btn2 = self.ui.pushButton_2
        btn3 = self.ui.pushButton_3

        btn1.clicked.connect(self.click_1)
        btn2.clicked.connect(self.click_2)
        btn3.clicked.connect(self.click_3)

    def click_1(self):
        min_h = self.ui.spinBox.value()
        min_s = self.ui.spinBox_2.value()
        min_v = self.ui.spinBox_3.value()
        max_h = self.ui.spinBox_4.value()
        max_s = self.ui.spinBox_5.value()
        max_v = self.ui.spinBox_6.value()
        self.mythread = MyThread((min_h, min_s, min_v, max_h, max_s, max_v))
        self.mythread.start()

    def click_2(self):
        if self.mythread.isRunning():
            self.mythread.stop()
            self.mythread.wait()

    def click_3(self):
        self.img_thread = ImageProcThread()
        self.img_thread.start()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = MyWindow()
    win.ui.show()
    app.exec_()
